from __future__ import absolute_import

import binascii
import io
import zipfile

import pyftype
from xscanner.modules import *

class ZipData(Data):
    def __init__(self):
        self._type = "zip"
        self._mime = "application/zip"

    def from_bytes(self, _bytes):
        super(ZipData, self).from_bytes(_bytes)

        self.zfile = zipfile.ZipFile(io.BytesIO(_bytes), "r")
        self._init_zipfiles()

    def _init_zipfiles(self):
        self._sub_files = {}
        self._strings = {}
        self._hexs = {}
        for name in self.zfile.namelist():
            bs = self.zfile.read(name)
            self._sub_files[name] = bs
            self._strings[name] = bs.decode("utf-8", errors="ignore")
            self._hexs[name] = binascii.hexlify(bs).decode("ascii")
        self.zfile.close()

    def match_subfile(self, name, nflag, content, cflag):
        for k in self._strings.keys():
            if nflag == MODE_STRING:
                if name not in k:
                    continue
            elif nflag == MODE_STRING_REGEX:
                if re.search(name, k) is None:
                    continue
            
            if cflag == MODE_STRING:
                if content in self._strings[k]:
                    return True
            elif cflag == MODE_STRING_REGEX:
                if re.search(content, self._strings[k]) is not None:
                    return True
            elif cflag == MODE_HEX:
                return content in self._hexs[k]
            elif cflag == MODE_HEX_REGEX:
                if re.search(content, self._hexs[k]) is not None:
                    return True

        return False

